<?php

namespace Pw\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Pw\MainBundle\Form\Type\RoleType;
use Pw\MainBundle\Form\Type\HeroEditType;
use Pw\MainBundle\Entity\Role;
class RoleController extends Controller
{
	public function indexAction(){
		$em = $this->getDoctrine()->getManager();
		$roles = $em->getRepository('PwMainBundle:Role')->findAll();
		return $this->render('PwMainBundle:Role:index.html.php',  array('roles' => $roles));
	}

	public function addAction(){
		$role = new Role();
		$form = $this->createForm(new RoleType(), $role);
		$request = $this->getRequest();
		if ($request->isMethod('POST')) {
			$form->bind($request);
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
				$role->doUpload();
				$em->persist($role);
				$em->flush();
				return $this->redirect($this->generateUrl('home'));
			}
		}
		return $this->render('PwMainBundle:Role:add.html.php',  array('form' => $form->createView()));		
	}

	public function editAction($heroId){
		$em = $this->getDoctrine()->getEntityManager();
		$hero = $em->getRepository('PwMainBundle:Hero')->find($heroId);
		if ($hero) {
			$form = $this->createForm(new HeroEditType(), $hero);
			$request = $this->getRequest();		
			if ($request->isMethod('POST')) {
				$form->bind($request);
				if ($form->isValid()) {
					$hero->doUpload();
					$em->flush();
					return $this->redirect($this->generateUrl('heroes_show'));
				}
			}
			return $this->render('PwMainBundle:Hero:edit.html.php',  array('form' => $form->createView(), 'heroId' => $heroId));
		}
		throw $this->createNotFoundException();
	}
	public function detailsAction($heroName){
		$em = $this->getDoctrine()->getEntityManager();
		$hero = $em->getRepository('PwMainBundle:Hero')->findByName($heroName);
		if ($hero) {

			return $this->render('PwMainBundle:Hero:details.html.php',  array('hero' => $hero));
		}
		throw $this->createNotFoundException();
	}
	public function deleteAction($heroId){
		$em = $this->getDoctrine()->getEntityManager();
		$hero = $em->getRepository('PwMainBundle:Hero')->find($heroId);
		if ($hero) {
			$em->remove($hero);
			$em->flush();			
		}
		return $this->redirect($this->generateUrl('heroes_show'));
	}
	
	public function getJsonAction($heroId){
		$em = $this->getDoctrine()->getEntityManager();
                $result = array();
                if ($heroId) {
                    $hero = $em->getRepository('PwMainBundle:Hero')->find($heroId);		
                    if ($hero) {
                        $result = $hero->getArray4JSON();
                    }
                } else {
                    $heroes = $em->getRepository('PwMainBundle:Hero')->findVisible();
                    foreach ($heroes as $h) {
                        $result[$h->getId()] = $h->getArray4JSON();
                    }
                }

		return new JsonResponse($result);
	}
}
